package com.lanhai.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;



public class BasicPostHttpHandler implements HttpHandler {
	
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        InputStream is = httpExchange.getRequestBody();
        
        String requestData = is2string(is);
        System.out.println("request: " + requestData);   
		Map<String,String> map = new HashMap<String,String>();
		map.put("name","name1");
		map.put("creatdate","2018-10-10");
		map.put("weather","tester1");
		map.put("sports","foolball");	
		Map<String,String> map2 = new HashMap<String,String>();
		map2.put("name","name2");
		map2.put("creatdate","2018-10-10");
		map2.put("weather","tester2");
		map2.put("sports","follball2");
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(map);
		list.add(map2);
		String response = JSON.toJSONString(list);
        System.out.println("response: " + response);        
        is.close();
        
        String queryParams = httpExchange.getRequestURI().getQuery();
        System.out.println(queryParams);
        
        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length);      
        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.flush();
        os.close();  
    }
	
    private String is2string(InputStream is) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
    
}
